<?php

/**
 * 滨江餐券
 * Class RestaurantQrcPayAction
 * @Auth    : piyechao
 * @Now     :2017/9/30 9:28
 */
class RestaurantQrcPayAction extends BaseAction
{
    private $sId;     //模块id
    private $tcode;   //终端编号
    private $appInfo; //应用配置信息
    private $mPrintSet;     //订餐打印小票的配置
    private $mPrintOrder;   //订餐打印小票的订单模型
    private $mPrintTerminal; //订餐打印小票的网点模型

    public function _initialize()
    {
        $otherAction = array("notify",'alipaynotify','alipayreturn');
        //不需要走构造函数方法
        if (!in_array(strtolower(ACTION_NAME), $otherAction)) {
            $this->sId = $this->_request('sid');
            $this->tcode = $this->_request('tcode');
            $this->mPrintSet = D('RestaurantPrintSet');
            $this->mPrintOrder = D('RestaurantPrintOrder');
            $this->mPrintTerminal = D('RestaurantPrintTerminal');

            if (!$this->sId) {
                $this->error('模块参数丢失!');
            }

            $this->appInfo = $this->mPrintSet->find($this->sId);
            $this->accountId = $this->appInfo['account_id'];
            if (!$this->appInfo) {
                $this->error('该模块暂未开通');
            }

            if (!$this->tcode) {
                $this->error('终端参数丢失!');
            }

        }

    }
    
    /**
     * 充值金额列表接口
     * @Auth    : piyechao
     * @Now     :2017/9/27 16:11
     */
    public function moneyList()
    {
        $field = 'mid,money';
        $moneyList = M('RestaurantPrintMoney')->field($field)->where(array('sid'=>$this->sId,'cut_off'=>0))->select();
        if($moneyList){
            $this->success($moneyList);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * 创建二维码接口
     * @Auth    : piyechao
     * @Now     :2017/9/27 16:11
     */
    public function createQrcode()
    {
        //订单金额
        $orderAmount = $this->_request('order_amount');
        if (!$orderAmount) {
            $this->ajaxReturn(array('status'=>'F','message'=>'金额不能空!'));
        }
        $orderId = $this->mPrintOrder->add(array('order_amount'=>$orderAmount));
        if(!$orderId){
            $this->ajaxReturn(array('status'=>'F','message'=>'订单生成失败!'));
        }

        $url = C('site_url').'/index.php?g=restaurant&m=restaurantQrcPay&a=index&sid='.$this->sId.'&tcode='.$this->tcode.'&order_id='.$orderId.'&order_amount='.$orderAmount;
        $data = array('url'=>$url,'order_amount'=>$orderAmount,'order_id'=>$orderId,);
        $this->success($data);
    }

    /**
     * 检查是否支付接口
     * @Auth    : piyechao
     * @Now     :2017/9/27 19:21
     */
    public function checkOrderStatus()
    {
        $orderId = $this->_request('order_id');
        if(!$orderId){
            $this->error('参数错误');
        }

        $field = 'order_sn,order_amount,terminal_name,website_name,update_time,status,pay_type';
        $order = M('RestaurantPrintOrder')->field($field)->find($orderId);
        if($order && $order['status'] == 1){
            $order['pay_type'] = $order['pay_type'] == 1 ? '微信' : '支付宝';
            $this->success($order);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * 通过终端编号获得网点终端信息接口
     * @Auth    : piyechao
     * @Now     :2017/9/28 14:51
     */
    public function getTerminalInfo()
    {
        $where = array('terminal_code'=>$this->tcode,'sid'=>$this->sId);
        $field = 'name,website_name';
        $data = $this->mPrintTerminal->where($where)->field($field)->find();
        if($data){
            $this->success($data);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * @param string $tips
     * @Auth    : piyechao
     * @Now     :2017/9/27 16:09
     */
    public function error($tips = '')
    {
        $this->ajaxReturn(array('ret_code' => 10000,'ret_msg' =>$tips));
    }

    /**
     * @param array $tips
     * @Auth    : piyechao
     * @Now     :2017/9/27 16:09
     */
    public function success($tips = array())
    {
        $this->ajaxReturn(array('ret_code' => 200,'ret_msg' =>'操作成功','data'=>$tips));
    }

    /**
     * 支付页面
     * @Auth    : piyechao
     * @Now     :2017/9/30 9:25
     */
    public function index()
    {
        $this->login(1);
        $data = $this->_get();
        $this->view($data);
    }

    /**
     * 创建订单
     * @Auth    : piyechao
     * @Now     :2017/9/28 14:48
     */
    public function createOrder()
    {
        //订单金额
        $orderAmount = $this->_request('order_amount');
        $orderId = $this->_request('order_id');
        if (!$orderId || !$orderAmount) {
            $this->ajaxReturn(array('status'=>'F','message'=>'参数错误1!'));
        }

        $order = $this->mPrintOrder->field('status')->find($orderId);
        if($order['status'] == 1){
            $this->ajaxReturn(array('status'=>'F','message'=>'已支付'));
        }

        //提交订单
        $where = array('terminal_code'=>$this->tcode,'sid'=>$this->sId);
        $field = 'name terminal_name,website_name';
        $data = $this->mPrintTerminal->where($where)->field($field)->find();
        $orderSnInfo = $this->getOrderSn('RestaurantQrcPay');
        if($this-> isWechatBrower()){
            $data['pay_type'] = 1;
            $data['openid'] = M('WechatUser')->where(array('wechat_user_id' => session("wechatUserId")))->getField("openid");
        }elseif($this-> isAlipayBrower()){
            $data['pay_type'] = 2;
        }else{
            $this->ajaxReturn(array('status' => 'F', 'message' => '暂只支持支付宝支付和微信支付'));
        }

        $data['account_id'] = $this->accountId;
        $data['order_id'] = $orderId;
        $data['sid'] = $this->sId;
        $data['terminal_code'] = $this->tcode;
        $data['order_amount'] = $orderAmount;
        $data['goods_amount'] = $orderAmount;
        $data['order_sn'] = $orderSnInfo['data'];
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = $this->mPrintOrder->update($data);
        if(!$res){
            $this->ajaxReturn(array('status' => 'F', 'message' => '创建订单失败'));
        }
        //调用支付接口
        $data['account_id'] = $this->appInfo['account_id'];
        if($this-> isWechatBrower()){
            $prepayData = $this->newPay($data['account_id'], $data['order_sn'], '餐券扫码支付', '', '');
            if (is_array($prepayData) && $prepayData['status'] == 'F') {
                $this->error(array('status' => 'F', 'message' => $prepayData['message']));
            }
            $result = $prepayData->windowPay();
            if ($result['status'] == 'S') {
                $this->ajaxReturn(array('status' => 'WS', 'message' => '调起微信成功', 'url' => $result['data'], 'order_id' => $orderId));
            } else {
                $this->error(array('status' => 'F', 'message' => $result['message']));
            }
        }elseif($this-> isAlipayBrower()){
            $notifyUrl = C('site_url')."/restaurant/restaurantQrcPay/alipayNotify";
            $returnUrl = C('site_url')."/restaurant/restaurantQrcPay/alipayReturn";
            $pay = $this->newPay($this->accountId,$data['order_sn'],'支付宝充值',$notifyUrl,$returnUrl);
            $payUrl = $pay->windowPay();
            $this->ajaxReturn(array('status' => 'AS','url' => $payUrl));
        }
    }

    /**
     * 支付宝支付成功返回页面
     */
    public function alipayReturn()
    {
        echo '支付成功页面';
    }

    /**
     * 支付宝异步处理
     */
    public function alipayNotify(){
        $data = $this->_post();
        $notify = array(
            'status' => 1,
            'transaction_id' => $data['trade_no'] ? $data['trade_no'] : '',
            'update_time' => date('Y-m-d H:i:s'),
            'pay_time'=>time(),
            'is_pay_notify'=>1,
            'pay_notify_time'=>time(),
        );
//        //支付宝存在使用集分宝或者红包的情况，一旦使用部分集分宝或者部分红包，支付宝会生成多笔
//        $fund_bill_list_arr =  json_decode($data['fund_bill_list'],true);
//        if($fund_bill_list_arr && count($fund_bill_list_arr)>1) {
//            $amont = 0;
//            $alipay_part_point = 0;
//            $alipay_part_coupon = 0;
//            $notify['part_num'] = 0;
//            foreach ($fund_bill_list_arr as $k => $v) {
//                if ($v['fund_channel'] == 'POINT' && $v['amount'] < $data['total_amount']) {
//                    $amont += $v['amount'];
//                    $alipay_part_point = 1;
//                }
//                if ($v['fund_channel'] == 'MCOUPON' && $v['amount'] < $data['total_amount']) {
//                    $amont += $v['amount'];
//                    $alipay_part_coupon = 1;
//                }
//            }
//            //有可能存在使用（集分宝+红包）刚好全额付款的情况，只能算一笔
//            if ($amont == $data['total_amount']) {
//                $notify['part_num'] = 1;
//                $notify['alipay_part_point'] = 1;
//                $notify['alipay_part_coupon'] = 1;
//            } elseif ($amont < $data['total_amount']) {
//                if ($alipay_part_point) {
//                    $notify['part_num']++;
//                    $notify['alipay_part_point'] = 1;
//                }
//                if ($alipay_part_coupon) {
//                    $notify['part_num']++;
//                    $notify['alipay_part_coupon'] = 1;
//                }
//            }
//        }
        $order_id = M('RestaurantPrintOrder')->where(array('order_sn'=>$data['out_trade_no']))->getField('order_id');
        if($order_id){
            M('RestaurantPrintOrder')->where(array('order_id'=>$order_id))->save($notify);
        }
        echo "SUCCESS";
    }

    /**
     * 微信支付回调
     * @param $order_id
     * @Auth    : piyechao
     * @Now     :2017/9/27 19:21
     */
    public function notify($order_id ,$account_id = 0)
    {
        $mOrder =M('RestaurantPrintOrder');
        $order = $mOrder->where(array('order_id'=>$order_id))->find();
        $data = array(
            'order_id' => $order['order_id'],
            'status' => 1,
            'update_time'=>date('Y-m-d H:i:s'),
        );
        $mOrder->save($data);
    }

    /**
     * 微信支付成功操作
     * @Auth    : piyechao
     * @Now     :2017/9/30 9:23
     */
    public function paySuccess()
    {
        $orderId = $this->_get('order_id');
        $url = U('/restaurant/restaurantQrcPay/wechatReturn',array('sid'=>$this->sId,'tcode'=>$this->tcode,'order_id'=>$orderId));
        $this->ajaxReturn(array('status' => 'S','message'=>'跳转支付成功页面','url' => $url));
    }

    /**
     * 微信支付成功跳转页面
     * @Auth    : piyechao
     * @Now     :2017/9/30 9:24
     */
    public function wechatReturn()
    {
        echo '支付成功页面';
    }

    public function test()
    {
        //订单金额
        $orderAmount = $this->_request('order_amount');
        if (!$orderAmount) {
            $this->ajaxReturn(array('status'=>'F','message'=>'金额不能空!'));
        }
        $orderId = $this->mPrintOrder->add(array('order_amount'=>$orderAmount));
        if(!$orderId){
            $this->ajaxReturn(array('status'=>'F','message'=>'订单生成失败!'));
        }

        $url = C('site_url').'/index.php?g=restaurant&m=restaurantQrcPay&a=index&sid='.$this->sId.'&tcode='.$this->tcode.'&order_id='.$orderId.'&order_amount='.$orderAmount;

        Vendor('phpqrcode.phpqrcode');
        $errorLevel = "L";
        //定义生成图片宽度和高度;默认为3
        $size = "4";
        //$url = "http://wap.alpha.greencampus.cc/index.php?g=restaurant&m=restaurantQrcPay&a=index&sid=1&tcode=T101174700024&order_id=55311&order_amount=0.02";
        QRcode::png($url, false, $errorLevel, $size);
        exit;
    }
}